package a51qindian.com.comprehensive.activity;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.li.interfaces.ISticky;
import com.li.recycleradapter.StickyItemDecoration;
import com.li.widget.DoubleTextView;
import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.adapter.CityDeviceAdapter;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.model.CityDeviceInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/10/16 0016
 * Description: 城市设备管理
 */

public class CityDeviceManagerActivity extends QDBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.recycler_device)
    RecyclerView mRecyclerDevice;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.dtv_all)
    DoubleTextView mDtvAll;
    @BindView(R.id.dtv_good)
    DoubleTextView mDtvGood;
    @BindView(R.id.dtv_bad)
    DoubleTextView mDtvBad;


    private List<CityDeviceInfo> mDeviceInfoList;
    private CityDeviceAdapter mDeviceAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_city_device_manager;
    }



    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        mDeviceInfoList = new ArrayList<>();
        mDeviceAdapter = new CityDeviceAdapter(this);
        mRecyclerDevice.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerDevice.setAdapter(mDeviceAdapter);
        mRecyclerDevice.addItemDecoration(new StickyItemDecoration(this, new ISticky() {
            @Override
            public boolean isFirstPosition(int pos) {
                return pos == 0 || !mDeviceInfoList.get(pos).getShopName().equals(
                        mDeviceInfoList.get(pos - 1).getShopName());
            }

            @Override
            public String getGroupName(int pos) {
                return mDeviceInfoList.get(pos).getShopName();
            }
        }));
        getDeviceList(mUid, Const.DEFAULT_PAGE);
        setSmartRefreshLayout(mLayoutRefresh);
    }
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        getDeviceList(mUid, Const.DEFAULT_PAGE);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        getDeviceList(mUid, String.valueOf(mPage + 1));
    }

    /**
     * 获取城市设备列表
     *
     * @param uid  用户编号
     * @param page 页数
     */
    private void getDeviceList(String uid, String page) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("page", page);
        ObservableHelper.createObservable(RetrofitCreator.createService().cityDeviceList(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        try {
                            JSONObject object = new JSONObject(s);

                            showToast(object.getString("info"));
                            JSONObject count=object.getJSONObject("count");
                            String good=count.getString("good_charge");
                            String bad=count.getString("bad_charge");
                            String all=count.getString("all_charge");

                            mDtvAll.setTxtRight(all);
                            mDtvGood.setTxtRight(good);
                            mDtvBad.setTxtRight(bad);
                            if (object.getInt("code") != 1) {
                                mLayoutRefresh.setLoadmoreFinished(true);
                                return;
                            }
                            object = object.getJSONObject("data");
                            Iterator<String> iterator = object.keys();
                            Type type = new TypeToken<List<CityDeviceInfo>>() {
                            }.getType();

                            List<CityDeviceInfo> deviceInfoList = new ArrayList<>();
                            while (iterator.hasNext()) {
                                String name = iterator.next();
                                List<CityDeviceInfo> c = new Gson()
                                        .fromJson(object.getString(name), type);
                                for (CityDeviceInfo device : c) {
                                    device.setShopName(name);
                                }
                                deviceInfoList.addAll(c);

                            }
                            if (mIsRefresh) {
                                mPage = 0;
                                mDeviceInfoList.clear();
                                mLayoutRefresh.setLoadmoreFinished(false);
                            } else {
                                mPage++;
                            }
                            stopRefreshLoad();
                            if (!mIsRefresh && object.length() < Const.DEFAULT_PAGE_SIZE) {
                                mLayoutRefresh.setLoadmoreFinished(true);
                            }
                            mDeviceInfoList.addAll(deviceInfoList);
                            mDeviceAdapter.setDeviceInfoList(mDeviceInfoList);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
